package com.codi.api.controller.goldlife;

import com.codi.base.exception.BaseAppException;
import com.codi.base.log.annotation.Loggable;
import com.codi.base.util.EqualsUtil;
import com.codi.base.util.JsonUtil;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.constant.RuleConstant;
import com.codi.bus.core.domain.Lookup;
import com.codi.bus.core.domain.OperationContent;
import com.codi.bus.core.domain.User;
import com.codi.bus.core.domain.UserBank;
import com.codi.bus.core.resultModel.AssetsResult;
import com.codi.bus.core.service.*;
import com.codi.bus.core.service.model.AssetFundModel;
import com.codi.bus.core.service.model.AssetPortfolioModel;
import com.codi.bus.core.service.model.FundSortModel;
import com.codi.bus.core.service.model.T0Model;
import com.codi.bus.core.util.ResultBeanUtil;
import com.codi.bus.exception.BaseException;
import com.codi.goldlife.external.databean.ResultBean;
import com.codi.message.constant.ErrorConstant;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 金品系统通过此接口调用基金相关内容
 * @Author: zengxl
 * @Description:
 * @Date: 2018/6/6 15:49
 */
@RestController
@Slf4j
public class GoldlifeController {
    @Autowired
    private UserService userService;
    @Autowired
    private BankService bankService;
    @Autowired
    private QueryService queryService;
    @Autowired
    private ProfitService profitService;
    @Autowired
    private T0Service t0Service;
    @Resource(name = "lookupService")
    private LookupService lookupService;
    @Autowired
    private FundCombinationService fundCombinationService;
    @Autowired
    private OperationContentService operationContentService;
    @Resource(name = "fundDetailService")
    private FundDetailService fundDetailService;
    @Resource
    private H5Service h5Service;
    /**
     * 获取认证信息
     *
     * @param request
     * @return
     */
    @Loggable
    @GetMapping("/goldlife/fund/getUserInfo")
    public ResultBean getUserInfo(HttpServletRequest request) {
        ResultBean bean = new ResultBean();
        String phone = request.getHeader("phone");
        String channelCode = GlobalConstant.GOLD_LIFE_CHANNEL;
        if (StringUtils.isBlank(phone)) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2102, "请求头缺失必要信息");
        }
        User user;
        try {
            user = userService.getUser(phone);
        } catch (BaseException e) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2101, "未查询到用户信息");
        }
        if (user == null) {
            user = new User();
            user.setUserMobile(phone);
            user.setUserName(phone);
            //生成随机密码,用户在基金APP上需要走忘记密码流程
            user.setLoginPassword(UUID.randomUUID().toString());
            //1:注册、2：绑卡
            user.setUserState(1);
            user.setCreateDate(new Date());
            user.setIsValid(true);
            user.setIsOrg(false);
            user.setUserFrom(channelCode);
            log.info("接口：/goldlife/fund/getUserInfo,用户未在基金系统注册,调用H5注册接口自动注册");
            user = h5Service.addUserByH5(user);
            if (user.getUserId() <= 0) {
                bean.setErrorCode(ErrorConstant.ERROR_NOT_LOGIN);
                bean.setSuccess(false);
                bean.setErrorMessage("用户未在基金系统注册,自动注册失败!");
                log.error("接口：/goldlife/fund/getUserInfo,用户未在基金系统注册,自动注册失败");
                return bean;
            }
            Map<String, String> result = Maps.newHashMap();
            result.put("userName", user.getUserName() == null ? "" : user.getUserName());
            result.put("userCardNo", user.getUserCard() == null ? "" : user.getUserCard());
            return ResultBeanUtil.setSuccessResult(bean, result);
        } else {
            Map<String, String> result = Maps.newHashMap();
            result.put("userName", user.getUserName() == null ? "" : user.getUserName());
            result.put("userCardNo", user.getUserCard() == null ? "" : user.getUserCard());
            return ResultBeanUtil.setSuccessResult(bean, result);
        }
    }

    @Loggable
    @GetMapping("/goldlife/fund/bankList")
    public ResultBean bankList(HttpServletRequest request) {
        ResultBean bean = new ResultBean();
        String phone = request.getHeader("phone");
        if (StringUtils.isBlank(phone)) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2102, "请求头缺失必要信息");
        }
        User user;
        try {
            user = userService.getUser(phone);
        } catch (BaseException e) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2101, "未查询到用户信息");
        }
        if (user == null) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2101, "未查询到用户信息");
        }
        List<Map<String, String>> result = Lists.newArrayList();
        List<UserBank> userBankList = bankService.getListByUserId(user.getUserId());
        if (userBankList.isEmpty()) {
            return ResultBeanUtil.setSuccessResult(bean, result);
        }
        for (UserBank bank : userBankList) {
            //柜台开卡不展示
            if (StringUtils.isBlank(bank.getCapitalMode()) || bank.getCapitalMode().equals(GlobalConstant.CAPITAL_MODE_COUNTER)) {
                continue;
            }
            Map<String, String> map = Maps.newHashMap();
            map.put("bankName", bank.getBankName() == null ? "" : bank.getBankName());
            map.put("bankCardNo", bank.getUserBankNo() == null ? "" : bank.getUserBankNo());
            map.put("cardType", "储蓄卡");
            result.add(map);
        }
        return ResultBeanUtil.setSuccessResult(bean, result);
    }

    /**
     * 我的资产
     *
     * @param request
     * @return
     */
    @Loggable
    @GetMapping("/goldlife/fund/myAssets")
    public ResultBean myAssets(HttpServletRequest request) {
        ResultBean bean = new ResultBean();
        String phone = request.getHeader("phone");
        if (StringUtils.isBlank(phone)) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2102, "请求头缺失必要信息");
        }
        User user;
        try {
            user = userService.getUser(phone);
        } catch (BaseException e) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2101, "未查询到用户信息");
        }
        if (user == null) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2101, "未查询到用户信息");
        }
        String allAssets = "";
        String profit = "";
        String accumulateProfit = "";
        String externalClientId = user.getExternalClientId();
        Map<String, Object> map = Maps.newHashMap();
        Map<String,String> detailMap = Maps.newHashMap();
        detailMap.put("t0Asset","");
        detailMap.put("fundAsset","");
        map.put("allAssets", allAssets);
        map.put("profit", profit);
        map.put("accumulateProfit", accumulateProfit);
        map.put("assetDetail",detailMap);
        if (StringUtils.isBlank(externalClientId)) {
            return ResultBeanUtil.setSuccessResult(bean, map);
        }
        List<UserBank> userBanks = bankService.getListByUserId(user.getUserId());
        if (userBanks == null || userBanks.size() == 0) {
            return ResultBeanUtil.setSuccessResult(bean, map);
        }
        int bankNum = 0;
        for (UserBank bank : userBanks) {
            if (StringUtils.isBlank(bank.getCapitalMode()) || bank.getCapitalMode().equals(GlobalConstant.CAPITAL_MODE_COUNTER)) {
                continue;
            }
            bankNum++;
        }
        //柜台开卡不展示资产
        if (bankNum == 0) {
            return ResultBeanUtil.setSuccessResult(bean, map);
        }

        AssetsResult assets = queryService.queryAssets(user.getUserId());
        if (assets != null) {
            if (assets.getTotalWorthValue() != null) {
                allAssets = String.valueOf(assets.getTotalWorthValue().setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());
                map.put("allAssets", allAssets==null?"":allAssets);
            }
            if (assets.getTotalTodayIncome() != null) {
                profit = String.valueOf(assets.getTotalTodayIncome().setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());
                map.put("profit", profit==null?"":profit);
            }
            if (assets.getTotalAccumIncome() != null) {
                accumulateProfit = String.valueOf(assets.getTotalAccumIncome().setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());
                map.put("accumulateProfit", accumulateProfit==null?"":accumulateProfit);
            }
            AssetFundModel t0 = assets.getWallet();
            String t0Total = null;
            if(t0 != null && t0.getTotalWorthValue() != null){
                t0Total = String.valueOf(t0.getTotalWorthValue().setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());
            }
            detailMap.put("t0Asset",t0Total==null?"":t0Total);
            AssetFundModel fundModel = assets.getFund();
            double fundTotal = 0;
            if(fundModel != null && fundModel.getTotalWorthValue() != null){
                fundTotal = fundModel.getTotalWorthValue().doubleValue();
            }
            AssetPortfolioModel portfolioModel = assets.getPortfolios();
            if(portfolioModel != null && portfolioModel.getPortfolioWorthValue() != null){
                fundTotal +=portfolioModel.getPortfolioWorthValue().doubleValue();
            }
            String fTotal = String.valueOf(new BigDecimal(fundTotal).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());
            detailMap.put("fundAsset",fTotal==null?"":fTotal);
            map.put("assetDetail", detailMap);
        }

        return ResultBeanUtil.setSuccessResult(bean, map);
    }

    /**
     * 收益记录
     *
     * @param request
     * @return
     */
    @Loggable
    @GetMapping("/goldlife/fund/profitRecordList")
    public ResultBean profitRecordList(HttpServletRequest request, @NonNull @RequestParam String beginDate, @NonNull @RequestParam String endDate) {
        ResultBean bean = new ResultBean();
        String phone = request.getHeader("phone");
        if (StringUtils.isBlank(phone)) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2102, "请求头缺失必要信息");
        }
        User user;
        try {
            user = userService.getUser(phone);
        } catch (BaseException e) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2101, "未查询到用户信息");
        }
        if (user == null) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2101, "未查询到用户信息");
        }
        List<Map<String, String>> result = profitService.getUserProfitList(user.getUserId().intValue(), beginDate, endDate);
        return ResultBeanUtil.setSuccessResult(bean, result);
    }

    /**
     * 理财首页接口数据
     *
     * @param request
     * @return
     */
    @Loggable
    @GetMapping("/goldlife/fund/financing")
    public ResultBean financing(HttpServletRequest request) {
        ResultBean bean = new ResultBean();
        String phone = request.getHeader("phone");
        if (StringUtils.isBlank(phone)) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2102, "请求头缺失必要信息");
        }
        User user;
        try {
            user = userService.getUser(phone);
        } catch (BaseException e) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2101, "未查询到用户信息");
        }
        if (user == null) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2101, "未查询到用户信息");
        }
        boolean isOrg = false;
        T0Model model;
        Lookup lookup = lookupService.getLookup(RuleConstant.APP_HOME_DISPLAY_T0);
        if (EqualsUtil.equals(1, lookup.getRuleStatus().intValue())) { // 使用自定义
            model = t0Service.queryT0Fund(isOrg, lookup.getRuleValue());
        } else { // 不是用自定义
            model = t0Service.queryTopRateFund(isOrg);
        }

        Map<String, Object> returnMap = Maps.newHashMap();
        returnMap.put("T0Recommend", model);
        returnMap.put("protfolioList", fundCombinationService.queryThreeCombinations());
        List<String> fundCodeList = Lists.newArrayList();
        List<Map<String, String>> jxjj = Lists.newArrayList();
        try {
            List<OperationContent>  contentList = operationContentService.queryOperationContentNew();
            if(!contentList.isEmpty()){
                Map<String, Object> fundCodeMap = null;
                for (OperationContent currentContent : contentList) {
                    if(StringUtils.isNotBlank(currentContent.getBlockName()) && "当前热点".equals(currentContent.getBlockName().trim())){
                        if (StringUtils.isNotBlank(currentContent.getExtraMap())) {
                            fundCodeMap = JsonUtil.parseJSON2Map(currentContent.getExtraMap());
                            if (fundCodeMap.get("fundCode") == null) {
                                continue;
                            }
                            fundCodeList.add(fundCodeMap.get("fundCode").toString());
                        }
                    }
                }
                if(fundCodeList.size() > 0){
                    List<FundSortModel>  fundSortModelList = fundDetailService.getFundNetValuePerformance(fundCodeList);
                    if(!fundSortModelList.isEmpty()){
                        for(FundSortModel model1:fundSortModelList){
                            Map<String, String> temp = Maps.newHashMap();
                            temp.put("fundCode",model1.getFundCode());
                            temp.put("fundName",model1.getFundName());
                            temp.put("dayIncrease",model1.getRate());
                            jxjj.add(temp);
                        }
                    }
                }
            }
        } catch (BaseAppException e) {
            e.printStackTrace();
        }

        returnMap.put("fundRecommend", jxjj);
        return ResultBeanUtil.setSuccessResult(bean, returnMap);
    }

    /**
     * 热销组合
     * @param request
     * @return
     */
    @Loggable
    @GetMapping("/goldlife/fund/hotPortfolio")
    public ResultBean hotPortfolio(HttpServletRequest request) {
        ResultBean bean = new ResultBean();
        String phone = request.getHeader("phone");
        if (StringUtils.isBlank(phone)) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2102, "请求头缺失必要信息");
        }
        User user;
        try {
            user = userService.getUser(phone);
        } catch (BaseException e) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2101, "未查询到用户信息");
        }
        if (user == null) {
            return ResultBeanUtil.setUnSuccessResult(bean, 2101, "未查询到用户信息");
        }
        Map<String, Object> returnMap = Maps.newHashMap();
        returnMap.put("protfolioList", fundCombinationService.queryThreeCombinations());
        return ResultBeanUtil.setSuccessResult(bean, returnMap);
    }
}
